import __config from 'env';
import $cache from '@/utils/cache.js'
module.exports = (url, data = {}, method = 'POST', showLoading = false, loadingText = '查询中,请稍后') => {
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				title: loadingText
			});
		}

		const token = $cache.get('token')
		const lang = uni.getStorageSync('showLanguage')
		uni.request({
			url: __config.baseUrl + '/api' + url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'token': token ? token : '',
				'lang': lang ? lang : 1
			},
			success(res) {
				if (res.statusCode == 404) {
					console.log(404)
					uni.showToast({
						title: '接口请求出错，请检查手机网络',
						icon: 'none'
					})
					reject();
				} else if (res.statusCode == 502) {
					console.log(502)
					uni.showToast({
						title: '服务启维护中，请稍后再来',
						icon: 'none'
					})
					reject();
				} else if (res.statusCode == 503) {
					console.log(503)
					uni.showToast({
						title: '503错误，服务未启动',
						icon: 'none'
					})
					reject();
				} else {
					if (res.data.code == 200) {
						if (res.data.show == 1) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						}
						resolve(res.data.data);
					} else {
						if (res.data.code == -1) {
							//登录失效，重新登录
							$cache.set('token', null);
							$cache.set('userInfo', null);
							return;
						}
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
						reject();
					}
				}
			},
			fail(error) {
				console.error('fail')
				uni.showToast({
					title: '接口请求出错：' + error.errMsg,
					icon: 'none'
				})
				reject(error);
			},
			complete(res) {
				uni.hideLoading();
			}
		});
	});
};